package com.tanklab.signature.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanklab.signature.common.util.HashUtil;
import com.tanklab.signature.common.util.ResultCode;
import com.tanklab.signature.common.util.TimeUtils;
import com.tanklab.signature.ds.req.AddRequestReq;
import com.tanklab.signature.ds.resp.CommonResp;
import com.tanklab.signature.entity.*;
import com.tanklab.signature.eth.ChainConnection;
import com.tanklab.signature.mapper.*;
import com.tanklab.signature.service.RequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Thread.sleep;

@Service
public class RequestServiceImpl extends ServiceImpl<RequestMapper, Request> implements RequestService {
    @Autowired
    private RequestMapper requestMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private ApprovallogsMapper approvallogsMapper;

//    @Autowired
//    private StudentMapper studentMapper;

    @Autowired
    private UserMapper userMapper;

//    @Override
//    public CommonResp addRequest(AddRequestReq addRequestReq){
//        CommonResp addRequestresp = new CommonResp();
//
//        QueryWrapper<File> wrapperFile = new QueryWrapper<>();
//        wrapperFile.select("id_file","id_fromrequest","name_file","file_path","created_time","file_key","student_id","tx_id");
//        List<File> files = fileMapper.selectList(wrapperFile);
//        File fileRequested= new File();
//        int flag = 0;
//        for(File file : files){//查找被请求的文件是否合法或存在
//            if(file.getName_file().equals(addRequestReq.getFileName())&&file.getFile_path().equals(addRequestReq.getFileStorageAddress())){
//                if(file.getStudent_id()!=addRequestReq.getFrom_studentId()){
//                    addRequestresp.setRet(ResultCode.NOT_MATCH_ERROR);
//                    addRequestresp.setData("no permission");//申请人id须与文件上传人id相同
//                    return addRequestresp;
//                }
//                else if(file.getId_fromrequest()>0){
//                    addRequestresp.setRet(ResultCode.NOT_MATCH_ERROR);
//                    addRequestresp.setData("already request");//文件已被申请
//                    return addRequestresp;
//                }
//                fileRequested = file;//找到目标文件
//                flag = 1;
//                break;
//            }
//        }
//        if(flag==0){
//            addRequestresp.setRet(ResultCode.NOT_MATCH_ERROR);//文件不存在
//            addRequestresp.setData("file does not exist");
//            return addRequestresp;
//        }
//
//        // 将填入的信息添加到新的Request对象中
//        Request request = new Request()
//                .setName_request(addRequestReq.getName_request())
//                .setType_request(addRequestReq.getType_request())
//                .setFrom_studentid(addRequestReq.getFrom_studentId())
//                .setName_file(addRequestReq.getFileName())
//                .setFile_path(addRequestReq.getFileStorageAddress())
//                .setCreated_time(TimeUtils.getCurrentTime());
//        // 查询自增id下一个是多少
//        QueryWrapper<Request> wrapper = new QueryWrapper<>();
//        wrapper.select("id_request");
//        List<Request> requests = requestMapper.selectList(wrapper);
//        Long maxId = Long.valueOf(0);
//        for (int i = 0; i < requests.size();i++){
//            Long perId = requests.get(i).getId_request();
//            if (perId > maxId) maxId = perId;
//        }
//        maxId = maxId + 1;
//        fileRequested.setId_fromrequest(maxId);
//
//        // 构造json
//        JSONObject requestInfo = new JSONObject();
//        requestInfo.put("requestId",maxId);
//        requestInfo.put("requestName",request.getName_request());
//        requestInfo.put("requestType",request.getType_request());
//        requestInfo.put("createdTime", TimeUtils.getCurrentTime());
//        requestInfo.put("fromRequest",request.getFrom_studentid());
//        requestInfo.put("fileName",addRequestReq.getFileName());
//        requestInfo.put("fileStorageAddress",addRequestReq.getFileStorageAddress());
//
//        // 计算请求的唯一key hash
//        String newRequestKey = HashUtil.hash_func(requestInfo.toString(),"MD5");
//        System.out.println("[New Request Key] "+newRequestKey);
//
//        String txId=null;
//        try{
//            txId= ChainConnection.sendHashToChain(newRequestKey);//上链
//        }catch (ChainConnection.BlockchainException e) {
//            System.err.println("上链失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//        if(txId==null){
//            addRequestresp.setRet(ResultCode.ERROR);
//            addRequestresp.setData("cannot connect to chain");
//            return addRequestresp;
//        }
//
//        request.setRequest_key(newRequestKey);
//        request.setTx_id(txId);
//
//        Student student = studentMapper.selectById(addRequestReq.getFrom_studentId());
//        student.setNum_request(student.getNum_request()+1);//学生申请数量加一
//
//        // 更新数据库
//        synchronized (this){
//            int insert = this.requestMapper.insert(request);
//            int update = this.fileMapper.updateById(fileRequested);
//            int updateStudent = this.studentMapper.updateById(student);
//        }
//
//        try {
//            sleep(1000);
//        }catch(Exception e){}
//        System.out.println("[New Transaction Id] "+txId);
//
////        System.out.println(maxId);
//        // 返回表单
//        addRequestresp.setRet(ResultCode.SUCCESS);
//        addRequestresp.setData("Add successfully! Transaction Id: "+txId);
//        return addRequestresp;
//
//    }
//
//    @Override
//    public CommonResp queryOneRequest(Long requestId){
//        CommonResp queryonerequestresp = new CommonResp();
//        Request  request = requestMapper.selectById(requestId);
//
//        if (request == null){
//            queryonerequestresp.setRet(ResultCode.NOT_MATCH_ERROR);
//            return queryonerequestresp;
//        }
//
//        JSONObject requestInfo = new JSONObject();
//
//        requestInfo.put("requestId",request.getId_request());
//        requestInfo.put("requestKey",request.getRequest_key());
//        requestInfo.put("txId",request.getTx_id());
//        requestInfo.put("createTime",request.getCreated_time());
//        requestInfo.put("fromStudentId",request.getFrom_studentid());
//        requestInfo.put("fromTeacherId",request.getFrom_teacherid());
//        requestInfo.put("requestType",request.getType_request());
//        requestInfo.put("requestName",request.getName_request());
//        requestInfo.put("state",request.getState());
//        requestInfo.put("fileName",request.getName_file());
//        requestInfo.put("filePath",request.getFile_path());
//
//
//
//        queryonerequestresp.setRet(ResultCode.SUCCESS);
//        queryonerequestresp.setData(requestInfo);
//        return queryonerequestresp;
//    }
//
//    @Override
//    public CommonResp queryAllRequest()
//    {
//        CommonResp queryrequestsresp = new CommonResp();
//        QueryWrapper<Request> wrapper = new QueryWrapper<>();
//        wrapper.select("id_request","name_request","type_request","from_studentid","from_teacherid","state","created_time","request_key","name_file","file_path","tx_id");
//        List<Request> requests = requestMapper.selectList(wrapper);
//
//        JSONObject requestsInfo = new JSONObject();
//        JSONArray requestsarr = new JSONArray();
//        for (int i=0;i<requests.size();i++){
//            JSONObject peroxinfo = new JSONObject();
//            peroxinfo.put("requestId",requests.get(i).getId_request());
//            peroxinfo.put("requestKey",requests.get(i).getRequest_key());
//            peroxinfo.put("createTime",requests.get(i).getCreated_time());
//            peroxinfo.put("fromStudentId",requests.get(i).getFrom_studentid());
//            peroxinfo.put("fromTeacherId",requests.get(i).getFrom_teacherid());
//            peroxinfo.put("requestType",requests.get(i).getType_request());
//            peroxinfo.put("requestName",requests.get(i).getName_request());
//            peroxinfo.put("state",requests.get(i).getState());
//            peroxinfo.put("fileName",requests.get(i).getName_file());
//            peroxinfo.put("filePath",requests.get(i).getFile_path());
//            peroxinfo.put("txId",requests.get(i).getTx_id());
//
//            requestsarr.add(peroxinfo);
//        }
//        requestsInfo.put("requestsInfo", requestsarr);
//        queryrequestsresp.setRet(ResultCode.SUCCESS);
//        queryrequestsresp.setData(requestsInfo);
//        return queryrequestsresp;
//    }
//
//    @Override
//    public CommonResp queryRequestByStudentId(Long studentId){
//        CommonResp queryrequestsresp = new CommonResp();
//        QueryWrapper<Request> wrapper = new QueryWrapper<>();
//        wrapper.select("id_request","name_request","type_request","from_studentid","from_teacherid","state","created_time","request_key","name_file","file_path","tx_id");
//        List<Request> requests = requestMapper.selectList(wrapper);
//
//        JSONObject requestsInfo = new JSONObject();
//        JSONArray requestsarr = new JSONArray();
//        for (int i=0;i<requests.size();i++){
//            if(requests.get(i).getFrom_studentid()==studentId) {
//                JSONObject peroxinfo = new JSONObject();
//                peroxinfo.put("requestId", requests.get(i).getId_request());
//                peroxinfo.put("requestKey", requests.get(i).getRequest_key());
//                peroxinfo.put("createTime", requests.get(i).getCreated_time());
//                peroxinfo.put("fromStudentId", requests.get(i).getFrom_studentid());
//                peroxinfo.put("fromTeacherId", requests.get(i).getFrom_teacherid());
//                peroxinfo.put("requestType", requests.get(i).getType_request());
//                peroxinfo.put("requestName", requests.get(i).getName_request());
//                peroxinfo.put("state", requests.get(i).getState());
//                peroxinfo.put("fileName",requests.get(i).getName_file());
//                peroxinfo.put("filePath",requests.get(i).getFile_path());
//                peroxinfo.put("txId",requests.get(i).getTx_id());
//
//                requestsarr.add(peroxinfo);
//            }
//        }
//        requestsInfo.put("requestsInfo", requestsarr);
//        queryrequestsresp.setRet(ResultCode.SUCCESS);
//        queryrequestsresp.setData(requestsInfo);
//        return queryrequestsresp;
//    }

    @Override
    public CommonResp queryPendingRequests(String approverOpenid) {
        CommonResp resp = new CommonResp();

        // 1. 获取审批者信息
        QueryWrapper<User> approverQuery = new QueryWrapper<>();
        approverQuery.eq("openid", approverOpenid);
        User approver = userMapper.selectOne(approverQuery);

        if (approver == null) {
            resp.setRet(ResultCode.USER_NOT_EXIST);
            resp.setMsg("用户不存在");
            return resp;
        }

        // 2. 查询所有待审批请求
        QueryWrapper<Request> requestQuery = new QueryWrapper<>();
        requestQuery.eq("status", "pending");
        List<Request> requests = requestMapper.selectList(requestQuery);

        // 3. 构造返回数据
        List<Map<String, Object>> requestList = new ArrayList<>();

        for (Request request : requests) {
//            Map<String, Object> requestData = new HashMap<>();
            JSONObject requestData = new JSONObject();
            requestData.put("requestId", request.getIdRequest());
            requestData.put("requestName", request.getNameRequest());
            requestData.put("requestType", request.getTypeRequest());
            requestData.put("createdTime", request.getCreatedTime());
            requestData.put("status", request.getStatus());
            requestData.put("comments", request.getComments());

            // 4. 获取文件信息
            if (request.getFileId() != null) {
                File file = fileMapper.selectById(request.getFileId());
                if (file != null) {
                    requestData.put("fileId", file.getIdFile());
                    requestData.put("fileName", file.getNameFile());
                    requestData.put("fileType", file.getFileType());
                }
            }

            // 5. 获取申请者信息
            if (request.getInitiatorOpenid() != null) {
                QueryWrapper<User> initiatorQuery = new QueryWrapper<>();
                initiatorQuery.eq("openid", request.getInitiatorOpenid());
                User initiator = userMapper.selectOne(initiatorQuery);

                if (initiator != null) {
                    requestData.put("initiatorId", initiator.getUser_id());
                    requestData.put("initiatorName", initiator.getUser_name());
                    requestData.put("initiatorOpenid", initiator.getOpenid());
                    requestData.put("initiatorAuthority", initiator.getAuthority());
                }
            }

            // 6. 判断当前用户是否有权限审批该请求
            boolean canApprove = true;

            // 不能审批自己的申请
            if (approverOpenid.equals(request.getInitiatorOpenid())) {
                canApprove = false;
            }

            // 如果是普通用户(申请者)，只能审批其他申请者的申请
            if (approver.getAuthority() == 0) { // 申请者权限
                // 获取请求发起者信息
                QueryWrapper<User> initiatorQuery = new QueryWrapper<>();
                initiatorQuery.eq("openid", request.getInitiatorOpenid());
                User initiator = userMapper.selectOne(initiatorQuery);

                if (initiator != null && initiator.getAuthority() != 0) {
                    // 如果发起者不是申请者，而是审批者，则申请者无权审批
                    canApprove = false;
                }
            }

            requestData.put("canApprove", canApprove);
            requestList.add(requestData);
        }

        // 7. 构造返回数据
//        Map<String, Object> data = new HashMap<>();
        JSONObject data = new JSONObject();
        data.put("requests", requestList);
        data.put("totalCount", requestList.size());
        data.put("approverName", approver.getUser_name());
        data.put("approverAuthority", approver.getAuthority());

        resp.setRet(ResultCode.SUCCESS);
        resp.setMsg("查询待审批请求列表成功");
        resp.setData(data);

        return resp;
    }

    @Override
    public CommonResp queryAllRequests(String openid, String status) {
        CommonResp resp = new CommonResp();

        // 获取当前用户信息
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.eq("openid", openid);
        User currentUser = userMapper.selectOne(userQuery);

        if (currentUser == null) {
            resp.setRet(ResultCode.USER_NOT_EXIST);
            resp.setMsg("用户不存在");
            return resp;
        }

        // 查询请求记录
        QueryWrapper<Request> requestQueryWrapper = new QueryWrapper<>();

        // 如果指定了状态，按状态筛选
        if (status != null && !status.isEmpty()) {
            requestQueryWrapper.eq("status", status);
        }

        // 按创建时间降序排列，最新的在前面
        requestQueryWrapper.orderByDesc("created_time");

        List<Request> requests = requestMapper.selectList(requestQueryWrapper);
        List<Map<String, Object>> resultList = new ArrayList<>();

        for (Request request : requests) {
            JSONObject requestInfo = new JSONObject();

            // 添加请求基本信息
            requestInfo.put("requestId", request.getIdRequest());
            requestInfo.put("requestName", request.getNameRequest());
            requestInfo.put("requestType", request.getTypeRequest());
            requestInfo.put("createdTime", request.getCreatedTime());
            requestInfo.put("status", request.getStatus());

            // 获取文件信息
            File file = null;
            if (request.getFileId() != null) {
                file = fileMapper.selectById(request.getFileId());
                if (file != null) {
                    requestInfo.put("fileName", file.getNameFile());
                    requestInfo.put("fileType", file.getFileType());
                    requestInfo.put("fileDescription", file.getFileDescription());
                    requestInfo.put("fileHash", file.getFileContentHash());
                } else {
                    requestInfo.put("fileName", "文件不存在");
                    requestInfo.put("fileType", "-");
                    requestInfo.put("fileDescription", "-");
                    requestInfo.put("fileHash", "-");
                }
            } else {
                requestInfo.put("fileName", "-");
                requestInfo.put("fileType", "-");
                requestInfo.put("fileDescription", "-");
                requestInfo.put("fileHash", "-");
            }

            // 获取发起人信息
            User initiator = null;
            if (request.getInitiatorOpenid() != null) {
                QueryWrapper<User> initiatorQuery = new QueryWrapper<>();
                initiatorQuery.eq("openid", request.getInitiatorOpenid());
                initiator = userMapper.selectOne(initiatorQuery);
            }

            if (initiator != null) {
                requestInfo.put("initiatorName", initiator.getUser_name());
                requestInfo.put("initiatorRole", initiator.getAuthority() == 0 ? "申请者" : "审批者");
            } else {
                requestInfo.put("initiatorName", "未知用户");
                requestInfo.put("initiatorRole", "未知");
            }

            // 获取审批记录信息（如果已审批）
            if ("approve".equals(request.getStatus()) || "reject".equals(request.getStatus())) {
                QueryWrapper<Approvallogs> logsQuery = new QueryWrapper<>();
                logsQuery.eq("id_request", request.getIdRequest());
                logsQuery.orderByDesc("action_time"); // 取最新的审批记录
                logsQuery.last("LIMIT 1");
                Approvallogs log = approvallogsMapper.selectOne(logsQuery);

                if (log != null && log.getApproverOpenid() != null) {
                    // 获取审批人信息
                    QueryWrapper<User> approverQuery = new QueryWrapper<>();
                    approverQuery.eq("openid", log.getApproverOpenid());
                    User approver = userMapper.selectOne(approverQuery);

                    if (approver != null) {
                        requestInfo.put("approverName", approver.getUser_name());
                        requestInfo.put("approverRole", approver.getAuthority() == 0 ? "申请者" : "审批者");
                    } else {
                        requestInfo.put("approverName", "未知审批人");
                        requestInfo.put("approverRole", "未知");
                    }

                    requestInfo.put("approveTime", log.getActionTime());
                    requestInfo.put("approveAction", log.getAction());
                    requestInfo.put("approveComments", log.getComments());
                }
            }

            // 判断当前用户对该请求的权限
            requestInfo.put("isInitiator", openid.equals(request.getInitiatorOpenid()));
            requestInfo.put("canApprove", canApprove(currentUser, request));

            resultList.add(requestInfo);
        }

        JSONObject data = new JSONObject();
        data.put("requests", resultList);
        data.put("totalCount", resultList.size());

        resp.setRet(ResultCode.SUCCESS);
        resp.setMsg("查询请求列表成功");
        resp.setData(data);
        return resp;
    }

    /**
     * 判断用户是否有权限审批请求
     */
    private boolean canApprove(User user, Request request) {
        // 不能审批自己的申请
        if (user.getOpenid().equals(request.getInitiatorOpenid())) {
            return false;
        }

        // 如果申请已经被审批，则无法再审批
        if (!"pending".equals(request.getStatus())) {
            return false;
        }

        // 获取请求发起者信息
        User initiator = null;
        if (request.getInitiatorOpenid() != null) {
            QueryWrapper<User> initiatorQuery = new QueryWrapper<>();
            initiatorQuery.eq("openid", request.getInitiatorOpenid());
            initiator = userMapper.selectOne(initiatorQuery);
        }

        // 如果是普通用户(申请者)，只能审批其他申请者的申请
        if (user.getAuthority() == 0) { // 申请者权限
            if (initiator != null && initiator.getAuthority() != 0) {
                // 如果发起者不是申请者，而是审批者，则申请者无权审批
                return false;
            }
        } else {
            // 审批者可以审批所有申请，或根据业务需要添加其他限制
        }

        return true;
    }
}
